﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using GalaSoft.MvvmLight;
using ASPItalia.ModelVirtualCasting.WP7.Services.ModelsManager;
using GalaSoft.MvvmLight.Messaging;
using System.Linq;
using GalaSoft.MvvmLight.Command;
using System.ComponentModel;
using System.Windows.Data;
using ASPItalia.ModelVirtualCasting.WP7.ViewModels.Messages;
using System.Runtime.Serialization;

namespace ASPItalia.ModelVirtualCasting.WP7.ViewModels
{
    public class MainPageViewModel : ViewModelBase
    {
        private ModelsManagerClient client;

        public MainPageViewModel()
            : base(Messenger.Default)
        {
            this.SearchCommand = new RelayCommand(Search, CanSearch);
        }

        public void LoadAsync()
        {
			SearchInProgessVisibility = Visibility.Visible;

            this.client = new ModelsManagerClient();
            this.client.GetAllModelsCompleted += new EventHandler<GetAllModelsCompletedEventArgs>(client_GetAllModelsCompleted);
            this.client.GetAllModelsAsync(new GetAllModelsRequest());
        }

        public void Abort()
        {
            // Annullo l'operazione in corso
            if (this.client != null)
                this.client.Abort();
            this.client = null;
        }

        private Model[] models;

        /// <summary>
        /// Lista delle modelle disponibili
        /// </summary>
        public Model[] Models
        {
            get { return models; }
            private set
            {
                if (models != value)
                {
                    models = value;
                    RaisePropertyChanged("Models");
                }
            }
        }

        private ICollectionView modelsView;

        /// <summary>
        /// Vista sulle modelle disponibili
        /// </summary>
        public ICollectionView ModelsView
        {
            get { return modelsView; }
            private set
            {
                if (modelsView != value)
                {
                    modelsView = value;
                    RaisePropertyChanged("ModelsView");
                }
            }
        }

        private string searchText;

        /// <summary>
        /// Testo da ricercare
        /// </summary>
        public string SearchText
        {
            get { return searchText; }
            set
            {
                if (searchText != value)
                {
                    searchText = value;
                    RaisePropertyChanged("SearchText");

                    this.SearchCommand.RaiseCanExecuteChanged();
                }
            }
        }

		Visibility searchInProgessVisibility;
		public Visibility SearchInProgessVisibility
		{
			get { return searchInProgessVisibility; }
			set
			{
				if (value != searchInProgessVisibility)
				{
					value = searchInProgessVisibility;
					RaisePropertyChanged("SearchInProgessVisibility");
				}
			}
		}

        /// <summary>
        /// Pulsante per avviare la ricerca
        /// </summary>
        public RelayCommand SearchCommand
        {
            get;
            private set;
        }

        private Model selectedModel;

        /// <summary>
        /// La modella selezionata
        /// </summary>
        public Model SelectedModel
        {
            get { return selectedModel; }
            set
            {
                if (selectedModel != value)
                {
                    selectedModel = value;
                    RaisePropertyChanged("SelectedModel");

                    if (value != null)
                        this.MessengerInstance.Send(new NavigationMessage(new Uri("/DetailsPage.xaml?fn=" + value.Multimedia[0].FileName, UriKind.Relative)));
                }
            }
        }

        private void Search()
        {
            if (this.ModelsView != null)
            {
                if (!String.IsNullOrEmpty(this.SearchText))
                    this.ModelsView.Filter = m => ((Model)m).FirstName.IndexOf(this.SearchText, StringComparison.CurrentCultureIgnoreCase) >= 0 || ((Model)m).LastName.IndexOf(this.SearchText, StringComparison.CurrentCultureIgnoreCase) >= 0;
                else
                    this.ModelsView.Filter = null;
            }
        }

        private bool CanSearch()
        {
            return true;
        }

        private void client_GetAllModelsCompleted(object sender, GetAllModelsCompletedEventArgs e)
        {
			SearchInProgessVisibility = Visibility.Collapsed;

            if (e.Cancelled) return;

            if (e.Error != null)
                HandleError(e.Error);
            else
            {
                this.Models = e.Result.Models.ToArray();

                // Creo la vista
                CollectionViewSource view = new CollectionViewSource();
                view.Source = this.Models;
                this.ModelsView = view.View;
            }
        }

        private void HandleError(Exception ex)
        {
            // Mostro il messaggio di errore
            this.MessengerInstance.Send(new NotificationMessage(ex.Message));
        }
    }
}
